<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="layout/default" lang="en">
<head>
  <title>Chat Room</title>
  <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
  <style>
    body {
      background-color: #f9f9f9;
    }
    .card {
      margin-top: 50px;
      border-radius: 10px;
      border: none;
      box-shadow: 0 2px 10px rgba(0,0,0,.1);
    }
    .card-header {
      background-color: #007bff;
      color: #fff;
      font-size: 24px;
      font-weight: bold;
      border-radius: 10px 10px 0 0;
    }
    .card-body {
      padding: 20px;
    }
    #chat-box {
      background-color: #fff;
      border-radius: 10px;
      padding: 10px;
    }
    #message-input {
      border-radius: 10px;
    }
    #user-list {
      background-color: #fff;
      border-radius: 10px;
      padding: 10px;
      height: 500px;
      overflow: auto;
      flex: auto;
    }
    #file-list {
      background-color: #fff;
      border-radius: 10px;
      padding: 10px;
      height: 400px;
      overflow: auto;
      flex: auto;
    }
    .modal {
      display: none;
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.5);
    }
    .modal-content {
      background-color: #fff;
      margin: auto;
      padding: 20px;
      border: 1px solid #888;
      width: 50%;
      height: 70%;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
      border-radius: 5px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
    .close {
      position: absolute;
      top: 10px;
      right: 10px;
      font-size: 20px;
      font-weight: bold;
      color: #888;
      cursor: pointer;
    }
    .file-input {
      margin-bottom: 20px;
      width: 100%;
    }
    .file-submit {
      padding: 10px 20px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    .file-submit:hover {
      background-color: #0069d9;
    }


  </style>
</head>
<body>
<div class="container">
  <div class="row">
    <div class="col-md-8">
      <div class="card">
        <div class="card-header">
          Chat Room
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-12">
              <div id="chat-box" style="height: 200px; overflow: auto;"></div>
            </div>
          </div>
          <div class="row mt-3">
            <div class="col-12">
              <button class="btn btn-primary" id="connect-button">连接</button>
              <button class="btn btn-primary" id="bulk-mailing">群发</button>
              <button class="btn btn-primary" id="close-button">关闭连接</button>
              <button class="btn btn-primary" onclick="showModal()">文件下载</button>
              <button class="btn btn-primary" onclick="function showModal_file()
              {
                      document.getElementById('myModal_file').style.display='block'
              }
              showModal_file()">文件上传</button>
              <div class="modal" id="myModal">
                <div class="modal-content">
                  <span class="close" onclick="hideModal()">&times;</span>
                  <p>服务器当前存储的文件</p >
                  <div id="file-list"></div>
                </div>
              </div>
              <div class="modal" id="myModal_file">
                <div class="modal-content">
                  <span class="close" onclick="function hideModal_file() {
                  document.getElementById('myModal_file').style.display='none'
                  }
                  hideModal_file()">&times;</span>
                  <p>文件上传</p>
                  <form id="file-match" enctype="multipart/form-data">
                    <input type="file" name="file" id="file-input" class="file-input">
                    <label><input type="checkbox" name="receiver" value="li"> li</label><br>
                    <label><input type="checkbox" name="receiver" value="feng"> feng</label><br>
                    <label><input type="checkbox" name="receiver" value="wang"> wang</label><br>
                  </form>
                  <button id="file-submit" class="file-submit" onclick="uploadFile()">Submit</button>
                  <div id="file-status"></div>
                </div>
              </div>
            </div>
          </div>
          <div class="row mt-3">
            <div class="col-10">
              <label for="message-input"></label><textarea  maxlength="200" class="form-control" id="message-input"></textarea>
            </div>
            <div class="col-2">
              <button class="btn btn-primary" id="send-button">Send</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div id="container"></div>
    <div class="col-md-4">
      <div class="card">
        <div class="card-header">
          Online Users
        </div>
        <div class="card-body">
          <div id="user-list"></div>
        </div>
      </div>
    </div>
  </div>
</div>
<script th:inline="javascript">



  /*<![CDATA[*/
  // Connect to WebSocket server
  var username = getUrlParam("username");
  var mode="all"
  var to_username=""

  var ws = new WebSocket("ws://" + window.location.host + "/chat/"+username);
  ws.onopen = function() {
    console.log("WebSocket connected");
  };
  ws.onclose=function (event)
  {
    console.log("Websocket closed:"+event.code+","+event.reason)
  }
  // 当接收到服务器发送的消息时触发
  ws.onmessage = function(event) {
    // 解析JSON格式的消息
    var message = JSON.parse(event.data);
    if("users" in message)
    {
      console.log("show online users");
      var users = message.users;
      showOnlineUsers(users)
    }
    else
    {
      // 显示消息
      var chatbox = document.getElementById("chat-box");
      var newMessage = document.createElement("p");
      newMessage.innerHTML = message.from + ": " + message.text;
      chatbox.appendChild(newMessage);
    }

  };
  // bulk mailing click
  var bulk_mailing_Button = document.getElementById("bulk-mailing");
  bulk_mailing_Button.onclick=function (){
    to_username=""
    mode="all"
    console.log("已设置群发")
  }
  // Connect button click
  var connectButton = document.getElementById("connect-button");
  connectButton.onclick = function() {
    if(ws.readyState===ws.CLOSED)
    {
      ws = new WebSocket("ws://" + window.location.host + "/chat/"+username);
      ws.onopen = function() {
        console.log("WebSocket connected");
      };
    }
  };
  // close button
  var close_button=document.getElementById("close-button")
  close_button.onclick=function ()
  {
    ws.close(1000,"连接正常关闭")
    ws.onclose=function (event)
    {
      console.log("Websocket closed:"+event.code+","+event.reason)
    }
  }
  // Send button click
  var sendButton = document.getElementById("send-button");
  var messageInput = document.getElementById("message-input");
  sendButton.onclick = function() {
    var message = {
      to: to_username,
      text: messageInput.value,
      mode: mode
    };
    var json=JSON.stringify(message)
    ws.send(json);
    if(mode==="single")
    {
      // 显示消息
      var chatbox = document.getElementById("chat-box");
      var newMessage = document.createElement("p");
      newMessage.innerHTML = username + ": " + messageInput.value;
      chatbox.appendChild(newMessage);
    }
    messageInput.value = "";
  };
  // 显示在线用户列表
  function showOnlineUsers(users) {
    var userList = document.getElementById("user-list");
    userList.innerHTML = "";
    for (var i = 0; i < users.length; i++) {
      var user = users[i];
      if(user.username!==username)
        userList.appendChild(createDiv(user.username)
        );
    }
  }
  function createDiv(content) {
    var newDiv = document.createElement("div");
    newDiv.setAttribute("display","flex")
    newDiv.setAttribute("justify-content","space-between")
    newDiv.setAttribute("align-items","center")
    var p = document.createElement("p");
    p.setAttribute("flex","1")
    p.setAttribute("margin-right","10px")
    p.innerText = content;
    var button = document.createElement("button");
    button.setAttribute("class","btn btn-primary")
    button.setAttribute("margin-left","10px")
    button.innerText="私聊"
    button.addEventListener("click", function() {
      to_username=p.innerText
      mode="single"
      console.log("当前私聊的用户为："+to_username)
    });
    newDiv.appendChild(p);
    newDiv.appendChild(button);
    return newDiv;
  }
  function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return decodeURIComponent(r[2]);
    } else {
      return null;
    }
  }
  function showModal() {
    document.getElementById("myModal").style.display = "block";
    var fileList = document.getElementById("file-list");
    fileList.innerHTML = "";
    var data=null
    let xhr=new XMLHttpRequest();
    xhr.open("GET","/fileList")
    xhr.send()
    xhr.onload=function (){
      if(xhr.status===200){
        data=JSON.parse(xhr.responseText)
        console.log("请求成功")
        for (var i = 0; i < data.length; i++) {
          var file = data[i];
          fileList.appendChild(createDiv_2(file))
        }
      }
      else
      {
        console.log("请求出错")
      }
    }
  }
  function createDiv_2(file) {
    var fileName=file.fileName
    var senderName=file.senderName
    var receiverName=file.receiverName
    var url=file.url
    var newDiv = document.createElement("div");
    newDiv.setAttribute("display","flex")
    newDiv.setAttribute("justify-content","space-between")
    newDiv.setAttribute("align-items","center")
    var p = document.createElement("p");
    p.setAttribute("flex","1")
    p.setAttribute("margin-right","10px")
    p.innerText = "文件名: "+fileName+" 发送者: "+senderName+" 接收者: "+receiverName;
    newDiv.appendChild(p);
    var button=document.createElement("button")
    button.innerText="下载"
    button.onclick=function (){
      var xhr=new XMLHttpRequest()
      xhr.open("GET","/download?url="+url,true)
      xhr.responseType="blob"
      xhr.onload=function (){
        if(this.status===200)
        {
          var blob=new Blob([this.response])
          var url_2=URL.createObjectURL(blob)
          var link=document.createElement("a")
          link.href=url_2
          link.download=fileName
          link.style.display="none"
          link.click()
        }
      }
      xhr.send()
    }
    newDiv.appendChild(button)
    return newDiv;
  }

  function hideModal() {
    document.getElementById("myModal").style.display = "none";
  }
  function uploadFile() {
    let form = document.getElementById("file-match");
    let file = document.getElementById("file-input").files[0];
    console.log(file)
    if (file) {
      let formData = new FormData(form);
      let request = new XMLHttpRequest();
      request.open("POST", "/upload");
      var checkboxes=document.getElementsByName("receiver")
      for(var i=0;i<checkboxes.length;i++)
      {
        if(checkboxes[i].type==="checkbox" && checkboxes[i].checked===true)
        {
          var message = {
            to: checkboxes[i].value,
            text: username+"给你发了文件",
            mode: "single"
          };
          var json=JSON.stringify(message)
          console.log("发送")
          ws.send(json);
        }
      }
      request.send(formData);
      request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
          document.getElementById("file-status").innerHTML = "File uploaded successfully!";
        } else {
          document.getElementById("file-status").innerHTML = "Error uploading file.";
        }
      }
    } else {
      document.getElementById("file-status").innerHTML = "Please select a file to upload.";
    }
  }

  /*]]>*/
</script>
</body>
</html>
